package com.hilinos.ftp.api;

import cn.hutool.core.io.FileUtil;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.EncryptUtils;
import com.hilinos.ftp.config.ServerConfig;
import com.hilinos.ftp.pojo.FilePojo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("file")
public class FileApi {

    @Autowired
    private ServerConfig serverConfig;

    @GetMapping("list")
    private List<FilePojo> list(String path) {

        List<FilePojo> files = new ArrayList<>();
        if (path == null) {
            path = "";
        }
        File file = BaseApi.getUserFileOrDir(path);
        if (file.isDirectory()) {
            for (File listFile : file.listFiles()) {
                files.add(toPojo(listFile, path));
            }
        } else {
            AssertUtils.throwEx("文件类型不支持");
        }
        files.sort((p1, p2) -> {
            if (p1.getFiletype() != p2.getFiletype()) {
                return p2.getFiletype() - p1.getFiletype();
            }
            return -(p2.getFilename().compareTo(p1.getFilename()));
        });
        return files;
    }

    @SneakyThrows
    @GetMapping("open")
    public void openFile(HttpServletRequest request, HttpServletResponse response, String path) {
        request.getRequestDispatcher("/static/" + BaseApi.getUserRelativePath(path)).forward(request, response);
    }

    @GetMapping("del")
    private void del(String path) {
        if (path == null) {
            path = "";
        }
        FileUtil.del(BaseApi.getUserRootDir() + path);
    }

    private FilePojo toPojo(File file, String path) {
        return FilePojo.builder()
                .fileid(EncryptUtils.getMd5(path + file.getName()))
                .filepath(path)
                .filename(file.getName())
                .filetype(file.isFile() ? 1 : 2)
                .filesize(file.length())
                .filepath(path + (path.endsWith("/") ? "" : "/") + file.getName())
                .filetypename(file.isFile() ? "文件" : "文件夹")
                .hasChildren(file.isDirectory() ? true : null)
                .children(file.isDirectory() ? new ArrayList<>() : null)
                .build();
    }

}
